#!/usr/bin/env python
"""
项目诊断脚本 - 检查常见的Django DRF项目问题
"""

import os
import sys
import subprocess
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    print("🐍 Python版本检查:")
    print(f"   Python版本: {sys.version}")
    if sys.version_info < (3, 8):
        print("   ⚠️  警告: Python版本可能过低，建议使用3.8+")
    else:
        print("   ✅ Python版本符合要求")

def check_django_installation():
    """检查Django和DRF安装"""
    print("\n📦 依赖包检查:")

    packages_to_check = [
        'django',
        'djangorestframework',
        'djangorestframework-simplejwt',
        'django-filter',
        'pillow'
    ]

    for package in packages_to_check:
        try:
            __import__(package.replace('-', '_'))
            print(f"   ✅ {package} 已安装")
        except ImportError:
            print(f"   ❌ {package} 未安装")

def check_project_structure():
    """检查项目结构"""
    print("\n📁 项目结构检查:")

    required_files = [
        'manage.py',
        'learn_drf/settings.py',
        'learn_drf/urls.py',
        'api_examples/models.py',
        'api_examples/views.py',
        'api_examples/serializers.py',
        'api_examples/urls.py',
    ]

    for file_path in required_files:
        if os.path.exists(file_path):
            print(f"   ✅ {file_path}")
        else:
            print(f"   ❌ {file_path} 缺失")

def check_django_settings():
    """检查Django设置"""
    print("\n⚙️  Django配置检查:")

    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learn_drf.settings')

        import django
        django.setup()

        from django.conf import settings

        # 检查关键配置
        checks = [
            ('DEBUG', getattr(settings, 'DEBUG', False)),
            ('INSTALLED_APPS包含rest_framework', 'rest_framework' in settings.INSTALLED_APPS),
            ('INSTALLED_APPS包含api_examples', 'api_examples' in settings.INSTALLED_APPS),
            ('数据库配置', bool(getattr(settings, 'DATABASES', {}))),
        ]

        for check_name, result in checks:
            if result:
                print(f"   ✅ {check_name}")
            else:
                print(f"   ❌ {check_name}")

    except Exception as e:
        print(f"   ❌ Django配置检查失败: {e}")

def check_migrations():
    """检查迁移状态"""
    print("\n🗄️  数据库迁移检查:")

    try:
        # 检查是否有未应用的迁移
        result = subprocess.run([
            sys.executable, 'manage.py', 'showmigrations', '--plan'
        ], capture_output=True, text=True, timeout=30)

        if result.returncode == 0:
            print("   ✅ 迁移检查成功")
            if '[ ]' in result.stdout:
                print("   ⚠️  有未应用的迁移")
            else:
                print("   ✅ 所有迁移已应用")
        else:
            print(f"   ❌ 迁移检查失败: {result.stderr}")

    except Exception as e:
        print(f"   ❌ 迁移检查异常: {e}")

def check_syntax():
    """检查Python语法"""
    print("\n🔍 语法检查:")

    python_files = [
        'api_examples/models.py',
        'api_examples/views.py',
        'api_examples/serializers.py',
        'api_examples/urls.py',
        'learn_drf/settings.py',
        'learn_drf/urls.py',
    ]

    for file_path in python_files:
        if os.path.exists(file_path):
            try:
                result = subprocess.run([
                    sys.executable, '-m', 'py_compile', file_path
                ], capture_output=True, text=True, timeout=10)

                if result.returncode == 0:
                    print(f"   ✅ {file_path}")
                else:
                    print(f"   ❌ {file_path}: {result.stderr}")
            except Exception as e:
                print(f"   ❌ {file_path}: 检查异常 {e}")

def check_django_system():
    """运行Django系统检查"""
    print("\n🏥 Django系统检查:")

    try:
        result = subprocess.run([
            sys.executable, 'manage.py', 'check', '--deploy'
        ], capture_output=True, text=True, timeout=30)

        if result.returncode == 0:
            print("   ✅ Django系统检查通过")
        else:
            print(f"   ❌ Django系统检查失败:")
            print(f"   错误: {result.stderr}")
            print(f"   输出: {result.stdout}")

    except Exception as e:
        print(f"   ❌ Django系统检查异常: {e}")

def try_import_views():
    """尝试导入视图模块"""
    print("\n🔧 模块导入测试:")

    modules_to_test = [
        'api_examples.models',
        'api_examples.views',
        'api_examples.serializers',
        'api_examples.urls',
    ]

    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learn_drf.settings')
        import django
        django.setup()

        for module_name in modules_to_test:
            try:
                __import__(module_name)
                print(f"   ✅ {module_name}")
            except Exception as e:
                print(f"   ❌ {module_name}: {e}")

    except Exception as e:
        print(f"   ❌ Django初始化失败: {e}")

def main():
    """主函数"""
    print("🔍 Django DRF 项目诊断工具")
    print("=" * 50)

    check_python_version()
    check_django_installation()
    check_project_structure()
    check_syntax()
    check_django_settings()
    try_import_views()
    check_migrations()
    check_django_system()

    print("\n" + "=" * 50)
    print("📋 诊断完成！")
    print("\n💡 如果发现问题，请根据上述检查结果进行修复。")
    print("💡 常见解决方案:")
    print("   1. 确保虚拟环境已激活")
    print("   2. 运行 pip install -r requirements.txt")
    print("   3. 运行 python manage.py makemigrations")
    print("   4. 运行 python manage.py migrate")

if __name__ == '__main__':
    main()
